#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <mosquittopp.h>
using namespace std;

class publish_mqtt : public mosqpp::mosquittopp
{
public:
    publish_mqtt(const char *id, const char *host, int port)
        : mosquittopp(id), host_(host), port_(port)
    {
    }

    bool connect()
    {
        int rc = mosquittopp::connect(host_.c_str(), port_, 60);
        return rc == MOSQ_ERR_SUCCESS;
    }

    void publish(const string &topic, const string &msg)
    {
        int rc = mosquittopp::publish(nullptr, topic.c_str(), msg.size(), msg.c_str());
        if (rc == MOSQ_ERR_SUCCESS)
        {
            cout << "publish " << topic << ":" << topic << endl;
        }
        else
        {
            cerr << "publish error" << endl;
        }
    }

protected:
    virtual void on_connect(int rc) override
    {
        cout << "on_connect rc: " << rc << endl;
    }

private:
    string host_;
    int port_;
};

int main(int argc, char *argv[])
{
    mosqpp::lib_init();
    publish_mqtt mqtt_pub("publish_test", "127.0.0.1", 1883);
    if (mqtt_pub.connect())
    {
        string topic = "test/topic";
        mqtt_pub.publish(topic, "hello world");
        // 同步输入发布msg
        while (true)
        {
            string msg;
            cin >> msg;
            mqtt_pub.publish(topic, msg);
            if (msg == "exit" || msg == "quit")
            {
                break;
            }
        }
    }

    this_thread::sleep_for(chrono::seconds(2));
    mosqpp::lib_cleanup();

    return 0;
}